const { Service } = require("egg");

class TopicService extends Service {
    async list() {
        return await this.app.model.Topic.findAll(
            {
                raw: true,
                where: { isDeleted: 0 },
                order: [['updatedAt', 'DESC']],
            }
        );
    }

    async teacherList() {
        try {
            const topicListWithTeachers = await this.ctx.model.Topic.findAll({
                include: [{
                    model: this.ctx.model.TopicTeacher,
                    as: 'teachers',
                }],
                where: { isDeleted: 0 },

                order: [['updatedAt', 'DESC']],
            });
            return topicListWithTeachers;
        } catch (error) {
            throw error;
        }
    }

    async materialList() {
        try {
            const topicListWithTeachers = await this.ctx.model.Topic.findAll({
                include: [{
                    model: this.ctx.model.TopicMaterial,
                    as: 'materials',
                }],
                where: { isDeleted: 0 },

                order: [['updatedAt', 'DESC']],
            });
            return topicListWithTeachers;
        } catch (error) {
            throw error;
        }
    }

    
    async lessonList() {
        try {
            const topicListWithLessons = await this.ctx.model.Topic.findAll({
                include: [{
                    model: this.ctx.model.TopicLesson,
                    as: 'lessons',
                }],
                where: { isDeleted: 0 },
                order: [['updatedAt', 'DESC']],
            });
            return topicListWithLessons;
        } catch (error) {
            throw error;
        }
    }

    async id(id) {
        const { ctx } = this;
        return await ctx.model.Topic.findOne({ where: { id } }).then((res) => {
            return res ? res.toJSON() : res;
        });
    }
    async create(data) {
        const { title, } = data;

        return await this.app.model.Topic.create({
            title,
        });
    }

    async delete(id) {
        return await this.app.model.Topic.update({ isDeleted: 1 },
            { where: { id } },
        );
    }

    async update(data) {
        const { title, id } = data;

        const TopicInfo = await this.app.model.Topic.findOne({
            where: { id },
        });
        if (TopicInfo) {
            const updatedTopic = await this.app.model.Topic.update({ title }, {
                where: { id: id },
            });
            return updatedTopic[0] ? updatedTopic[0] : null;
        }
        return null;
    }
}

module.exports = TopicService;
